<template>
  <div>
    <div class="header">
      <div class="logo">
        <span @click="goHome" v-html="projectName+'接口文档'"></span>
      </div>
      <div class="headerMenu">
        <!--头部右边设置-->
        <div class="setting">
          <div class="item" @click="goHome">
            <i class="iconfont">&#xe61c;</i> 主页
          </div>
        </div>
      </div>
    </div>
    <div class="preview content">
      <!--接口列表-->
      <div class="menu scrollbar">
        <el-input placeholder="输入关键字进行过滤" v-model="filterApiText" suffix-icon="el-icon-search">
        </el-input>
        <div class="opt">
        </div>
        <el-tree
          class="filter-tree"
          :data="apiList"
          :props="defaultProps"
          :highlight-current="true"
          :expand-on-click-node="false"
          @node-click="handleTreeClick"
          default-expand-all
          :filter-node-method="filterNode"
          ref="apiTree">
        </el-tree>

      </div>
      <!--接口详情-->
      <div class="detial scrollbar">
        <!--接口名称-->
        <div class="api-title">
          <span v-html="api.name||'接口名称'"></span>
          <el-tooltip placement="right" v-show="api.name">
            <div slot="content">
              作者：{{api.creater}} <br/>
              修改日期：{{formatDateTime(api.updateDate)}}
            </div>
            <i class="el-icon-info"></i>
          </el-tooltip>
        </div>
        <!--接口描述-->
        <div class="description" v-html="api.description?api.description.replace(/\n/g,'<br>'):'接口描述'"></div>
        <!--接口url-->
        <div class="url">
          <h3>请求URL</h3>
        </div>
        <div class="url-content">
          <el-tag type="primary">{{api.reqType?api.reqType.toUpperCase():'请求类型'}}</el-tag>
          <el-input class="apiIp" size="small" placeholder="接口服务地址" v-model="apiIp" v-if="apiIpInput">
            <template slot="prepend">http://</template>
            <template slot="append" v-if="api.url">{{api.url}}</template>
          </el-input>
          <el-tag type="info" v-else>{{'http://localhost:8080/'+api.url}}</el-tag>
          <el-button class="mybtn" type="warning" size="mini" :data-clipboard-text="apiIp+api.url"
                     @click="testApi(api.url)">
            <i class="iconfont">&#xe60d;</i>
          </el-button>
        </div>
        <!--接口请求参数-->
        <h3>请求参数</h3>
        <div class="reqParams">
          <el-table :data="reqParamsData" size="medium" border>
            <el-table-column prop="name" label="参数名" width="180"></el-table-column>
            <el-table-column prop="type" label="类型" width="100"></el-table-column>
            <el-table-column prop="isNeed" label="是否必须" width="90">
              <template slot-scope="scope">
                <el-tag type="danger" size="small" close-transition v-if="scope.row.isNeed">是</el-tag>
                <el-tag type="info" size="small" close-transition v-else>否</el-tag>
              </template>
            </el-table-column>
            <el-table-column label="描述">
              <template slot-scope="scope">
                <span v-html="scope.row.description.replace(/\n/g,'<br>')"></span>
              </template>
            </el-table-column>
            <el-table-column label="备注">
              <template slot-scope="scope">
                <span v-html="scope.row.remark?scope.row.remark.replace(/\n/g,'<br>'):''"></span>
              </template>
            </el-table-column>
            <el-table-column label="模拟参数值" width="350" v-if="showMock">
              <template slot-scope="scope">
                <el-input type="textarea" placeholder="请输入测试值" v-model="scope.row.mockValue" autosize></el-input>
              </template>
            </el-table-column>
          </el-table>
        </div>
        <!--接口请求头-->
        <div class="reqHeader" v-if="reqHeaderData.length>0">
          <h3>请求头</h3>
          <el-table :data="reqHeaderData" size="medium" border style="width: 100%">
            <el-table-column prop="key_" label="key" width="150">
            </el-table-column>
            <el-table-column prop="value_" label="value">
              <template slot-scope="scope">
                <el-input type="textarea" placeholder="请输入测试值" v-model="scope.row.value_" autosize></el-input>
              </template>
            </el-table-column>
            <el-table-column label="描述" width="250">
            </el-table-column>
          </el-table>
        </div>
        <!--接口响应数据-->
        <h3>响应参数</h3>
        <el-table :data="respParamsData" size="medium" border>
          <el-table-column prop="name" label="参数名" width="180"></el-table-column>
          <el-table-column prop="description" label="参数含义"></el-table-column>
          <el-table-column prop="remark" label="备注"></el-table-column>
        </el-table>
        <!--接口返回示例-->
        <h3>返回示例</h3>
        <div class="scrollbar" id="preview-respJson">
          <div class="no-content">暂无数据</div>
        </div>
      </div>
    </div>
  </div>
</template>
<style lang="scss">
  .preview.content {
    .detial {
      .api-title {
        font-weight: bold;
        font-size: 22px;
        i {
          font-size: 12px;
          color: #909399;
        }
      }
      h3 {
        margin: 25px 0 15px;
        font-weight: bold;
        font-size: 16px;
      }
      .description {
        padding: 10px 0;
        font-size: 14px;
      }
      .url-val {
        letter-spacing: 1px;
        font-size: 14px;
        padding-right: 10px;
      }
      .url-content {
        display: flex;
        align-items: center;
        .apiIp {
          width: 500px;
          margin-right: 8px;
        }
        .el-tag {
          margin-right: 8px;
        }
      }
    }
    thead tr {
      background: #f5f7fa;
    }
    #preview-respJson {
      border: 1px solid #ebeef5;
      font-size: 14px;
      padding: 20px 30px;
      box-sizing: border-box;
      .no-content {
        text-align: center;
        color: #606266;
      }
    }
  }
</style>
<script>
  import router from '../router'
  import http from '../api/http'
  import util from '../util'
  import store from '../util/store'
  import Clipboard from 'clipboard'
  import axios from 'axios'
  import qs from 'qs'
  import {server} from '../api/config'
  import '../util/jquery-1.11.1.min'
  import '../util/jquery.jsonview'
  import '../scss/jquery.jsonview.css'

  export default {
    data() {
      return {
        projectName: store.get('projectName'),
        filterApiText: '',
        apiList: [],
        api: {
          pid: '',
          name: '',
          description: '',
          reqType: '',
          url: '',
        },
        reqParamsData: [],
        reqHeaderData: [],
        respParamsData: [],
        respData: [],
        defaultProps: {
          children: 'children',
          label: 'label'
        },
        showMock: false,
        apiIp: store.get('apiIp' + store.get('projectId')) || '',
        apiIpInput: store.get('apiIp' + store.get('projectId')) ? true : false
      };
    },
    watch: {
      filterApiText(val) {
        this.$refs.apiTree.filter(val)
      }
    },
    mounted() {
      this.getApis()
    },
    methods: {
      getApis() {
        http.get('api/list', {id: store.get('projectId')}).then(response => {
          this.apiList = util.toTreeData(response.data)
        })
      },
      // 筛选接口
      filterNode(value, data) {
        if (!value) return true;
        return data.label.indexOf(value) !== -1;
      },
      // 选中接口
      handleTreeClick(obj) {
        if (obj.pid != 0) {
          this.api = obj
        } else {
          this.api = {}
        }
        this.reqParamsData = obj.reqParam ? JSON.parse(obj.reqParam) : []
        this.reqHeaderData = obj.reqHeader ? JSON.parse(obj.reqHeader) : []
        this.respParamsData = obj.respData ? JSON.parse(obj.respData) : []
        $('#preview-respJson').html(`<div class="no-content">暂无数据</div>`)
      },
      // 测试api
      testApi(url) {
        if (!this.apiIp) {
          this.apiIpInput = true
          return
        } else {
          store.set('apiIp' + store.get('projectId'), this.apiIp)
        }
        this.showMock = true
        let reqType = this.api.reqType
        let apiUrl = 'http://' + this.apiIp + this.api.url
        let params = util.handleReqParams(this.reqParamsData)
        let headers = util.handleReqHeaders(this.reqHeaderData)
        if (reqType == 'get') {
          axios({
            method: 'get',
            url: apiUrl,
            params: params,
            headers: headers
          }).then(response => {
            $("#preview-respJson").jsonViewer(response.data)
          })
        } else if (reqType == 'post') {
          axios({
            method: 'post',
            url: apiUrl,
            data: qs.stringify(params),
            headers: headers
          }).then(response => {
            $("#preview-respJson").jsonViewer(response.data)
          })
        }

        /*var clipboard = new Clipboard('.mybtn', {
          text: () => {
            return 'http://' + this.apiIp + this.api.url;
          }
        })
        clipboard.on('success', (e) => {
          e.clearSelection()
          clipboard.destroy()
        });*/
      },
      goHome() {
        // 判断是否是游客
        router.push('/')
      },
      formatDateTime(val) {
        if (val) {
          return util.formatDateTime(val)
        } else {
          return '--'
        }
      },
    }
  };

</script>
